package com.yunchang.spring.visitor.core.utils;

import org.apache.commons.lang.ArrayUtils;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * Map工具类
 *
 * @version 1.0
 */
public abstract class MapUtil {
    /**
     * 过滤参数。
     *
     * @param properties 参数集合
     * @return 返回过滤后的参数集合
     */
    public static Map filterParams(Map properties, String[] allowKeys, boolean allowNullValue) {
        if (properties == null || properties.isEmpty()) {
            return properties;
        }
        if (allowKeys == null || allowKeys.length == 0) {
            return properties;
        }
        Map filterProperties = new HashMap();
        for (Object key : properties.keySet()) {
            if (!ArrayUtils.contains(allowKeys, key)) {
                continue;
            }
            if (allowNullValue || properties.get(key) != null) {
                filterProperties.put(key, properties.get(key));
            }
        }
        return filterProperties;
    }


    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Object> sortMap = new TreeMap<String, Object>(
                new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }

/*    public static void main(String[] args) {
        Map<String, Object> requestMap = new HashMap<String, Object>();
        requestMap.put("cpFee", new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP));
        requestMap.put("uid", new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP));
        requestMap.put("gameId", new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP));
        System.out.println(ParseJson.encodeJson(MapUtil.sortMapByKey(requestMap)));
    }*/
}

// 比较器类
class MapKeyComparator implements Comparator<String> {
    @Override
    public int compare(String str1, String str2) {
        return str1.compareTo(str2);
    }
}


